{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c0bc3390-4bed-49d3-96ce-072badb4110b",
   "metadata": {},
   "source": [
    "# How to do \"self-querying\" retrieval\n",
    "\n",
    ":::info Prerequisites\n",
    "\n",
    "This guide assumes familiarity with the following concepts:\n",
    "\n",
    "- [Retrievers](/docs/concepts#retrievers)\n",
    "- [Vector stores](/docs/concepts#vectorstores)\n",
    "\n",
    ":::\n",
    "\n",
    "A self-querying retriever is one that, as the name suggests, has the ability to query itself. Specifically, given any natural language query, the retriever uses an LLM to write a structured query and then applies that structured query to its underlying vector store. This allows the retriever to not only use the user-input query for semantic similarity comparison with the contents of stored documents but to also extract filters from the user query on the metadata of stored documents and to execute those filters.\n",
    "\n",
    "![](../../static/img/self_querying.jpeg)\n",
    "\n",
    ":::info\n",
    "\n",
    "Head to [Integrations](/docs/integrations/retrievers/self_query) for documentation on vector stores with built-in support for self-querying.\n",
    "\n",
    ":::\n",
    "\n",
    "## Get started\n",
    "\n",
    "For demonstration purposes, we'll use an in-memory, unoptimized vector store. You should swap it out for a supported production-ready vector store when seriously building.\n",
    "\n",
    "The self-query retriever requires you to have the [`peggy`](https://www.npmjs.com/package/peggy) package installed as a peer dep, and we'll also use OpenAI for this example:\n",
    "\n",
    "```{=mdx}\n",
    "import Npm2Yarn from '@theme/Npm2Yarn';\n",
    "\n",
    "<Npm2Yarn>\n",
    "  peggy @langchain/openai\n",
    "</Npm2Yarn>\n",
    "```\n",
    "\n",
    "We've created a small demo set of documents that contain summaries of movies:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "beec3e35-3750-408c-9f2a-d92cf0a9a321",
   "metadata": {},
   "outputs": [],
   "source": [
    "import \"peggy\";\n",
    "import { Document } from \"@langchain/core/documents\";\n",
    "\n",
    "/**\n",
    " * First, we create a bunch of documents. You can load your own documents here instead.\n",
    " * Each document has a pageContent and a metadata field. Make sure your metadata matches the AttributeInfo below.\n",
    " */\n",
    "const docs = [\n",
    "  new Document({\n",
    "    pageContent:\n",
    "      \"A bunch of scientists bring back dinosaurs and mayhem breaks loose\",\n",
    "    metadata: { year: 1993, rating: 7.7, genre: \"science fiction\", length: 122 },\n",
    "  }),\n",
    "  new Document({\n",
    "    pageContent:\n",
    "      \"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\",\n",
    "    metadata: { year: 2010, director: \"Christopher Nolan\", rating: 8.2, length: 148 },\n",
    "  }),\n",
    "  new Document({\n",
    "    pageContent:\n",
    "      \"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea\",\n",
    "    metadata: { year: 2006, director: \"Satoshi Kon\", rating: 8.6 },\n",
    "  }),\n",
    "  new Document({\n",
    "    pageContent:\n",
    "      \"A bunch of normal-sized women are supremely wholesome and some men pine after them\",\n",
    "    metadata: { year: 2019, director: \"Greta Gerwig\", rating: 8.3, length: 135 },\n",
    "  }),\n",
    "  new Document({\n",
    "    pageContent: \"Toys come alive and have a blast doing so\",\n",
    "    metadata: { year: 1995, genre: \"animated\", length: 77 },\n",
    "  }),\n",
    "  new Document({\n",
    "    pageContent: \"Three men walk into the Zone, three men walk out of the Zone\",\n",
    "    metadata: {\n",
    "      year: 1979,\n",
    "      director: \"Andrei Tarkovsky\",\n",
    "      genre: \"science fiction\",\n",
    "      rating: 9.9,\n",
    "    },\n",
    "  }),\n",
    "];"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99771131-1efb-42e2-95f8-2aaa95f37677",
   "metadata": {},
   "source": [
    "### Creating our self-querying retriever\n",
    "\n",
    "Now we can instantiate our retriever. To do this we'll need to provide some information upfront about the metadata fields that our documents support and a short description of the document contents."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7832ca43-cc17-4375-bf4e-679b99584568",
   "metadata": {},
   "outputs": [],
   "source": [
    "import { OpenAIEmbeddings, OpenAI } from \"@langchain/openai\";\n",
    "import { FunctionalTranslator } from \"@langchain/core/structured_query\";\n",
    "import { MemoryVectorStore } from \"langchain/vectorstores/memory\";\n",
    "import { SelfQueryRetriever } from \"langchain/retrievers/self_query\";\n",
    "import type { AttributeInfo } from \"langchain/chains/query_constructor\";\n",
    "\n",
    "/**\n",
    " * We define the attributes we want to be able to query on.\n",
    " * in this case, we want to be able to query on the genre, year, director, rating, and length of the movie.\n",
    " * We also provide a description of each attribute and the type of the attribute.\n",
    " * This is used to generate the query prompts.\n",
    " */\n",
    "const attributeInfo: AttributeInfo[] = [\n",
    "  {\n",
    "    name: \"genre\",\n",
    "    description: \"The genre of the movie\",\n",
    "    type: \"string or array of strings\",\n",
    "  },\n",
    "  {\n",
    "    name: \"year\",\n",
    "    description: \"The year the movie was released\",\n",
    "    type: \"number\",\n",
    "  },\n",
    "  {\n",
    "    name: \"director\",\n",
    "    description: \"The director of the movie\",\n",
    "    type: \"string\",\n",
    "  },\n",
    "  {\n",
    "    name: \"rating\",\n",
    "    description: \"The rating of the movie (1-10)\",\n",
    "    type: \"number\",\n",
    "  },\n",
    "  {\n",
    "    name: \"length\",\n",
    "    description: \"The length of the movie in minutes\",\n",
    "    type: \"number\",\n",
    "  },\n",
    "];\n",
    "\n",
    "\n",
    "\n",
    "/**\n",
    " * Next, we instantiate a vector store. This is where we store the embeddings of the documents.\n",
    " * We also need to provide an embeddings object. This is used to embed the documents.\n",
    " */\n",
    "const embeddings = new OpenAIEmbeddings();\n",
    "const llm = new OpenAI();\n",
    "const documentContents = \"Brief summary of a movie\";\n",
    "const vectorStore = await MemoryVectorStore.fromDocuments(docs, embeddings);\n",
    "const selfQueryRetriever = SelfQueryRetriever.fromLLM({\n",
    "  llm,\n",
    "  vectorStore,\n",
    "  documentContents,\n",
    "  attributeInfo,\n",
    "  /**\n",
    "   * We need to use a translator that translates the queries into a\n",
    "   * filter format that the vector store can understand. We provide a basic translator\n",
    "   * translator here, but you can create your own translator by extending BaseTranslator\n",
    "   * abstract class. Note that the vector store needs to support filtering on the metadata\n",
    "   * attributes you want to query on.\n",
    "   */\n",
    "  structuredQueryTranslator: new FunctionalTranslator(),\n",
    "});"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c66f4c8-3682-46ac-8f17-0839194888a3",
   "metadata": {},
   "source": [
    "### Testing it out\n",
    "\n",
    "And now we can actually try using our retriever!\n",
    "\n",
    "We can ask questions like \"Which movies are less than 90 minutes?\" or \"Which movies are rated higher than 8.5?\".\n",
    "We can also ask questions like \"Which movies are either comedy or drama and are less than 90 minutes?\".\n",
    "The translator within the retriever will automatically convert these questions into vector store filters that can be used to retrieve documents."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "21c5df28-ea78-4f4e-99d6-489c864d1a04",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\n",
       "  Document {\n",
       "    pageContent: \u001b[32m\"Toys come alive and have a blast doing so\"\u001b[39m,\n",
       "    metadata: { year: \u001b[33m1995\u001b[39m, genre: \u001b[32m\"animated\"\u001b[39m, length: \u001b[33m77\u001b[39m }\n",
       "  }\n",
       "]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await selfQueryRetriever.invoke(\n",
    "  \"Which movies are less than 90 minutes?\"\n",
    ");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "228e5d70-d4cf-43bb-bc8e-3d6f11e784f2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\n",
       "  Document {\n",
       "    pageContent: \u001b[32m\"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception\"\u001b[39m... 16 more characters,\n",
       "    metadata: { year: \u001b[33m2006\u001b[39m, director: \u001b[32m\"Satoshi Kon\"\u001b[39m, rating: \u001b[33m8.6\u001b[39m }\n",
       "  },\n",
       "  Document {\n",
       "    pageContent: \u001b[32m\"Three men walk into the Zone, three men walk out of the Zone\"\u001b[39m,\n",
       "    metadata: {\n",
       "      year: \u001b[33m1979\u001b[39m,\n",
       "      director: \u001b[32m\"Andrei Tarkovsky\"\u001b[39m,\n",
       "      genre: \u001b[32m\"science fiction\"\u001b[39m,\n",
       "      rating: \u001b[33m9.9\u001b[39m\n",
       "    }\n",
       "  }\n",
       "]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await selfQueryRetriever.invoke(\n",
    "  \"Which movies are rated higher than 8.5?\"\n",
    ");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8244591e-97b5-4aba-b1e5-fe5e1996cb99",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\n",
       "  Document {\n",
       "    pageContent: \u001b[32m\"A bunch of normal-sized women are supremely wholesome and some men pine after them\"\u001b[39m,\n",
       "    metadata: { year: \u001b[33m2019\u001b[39m, director: \u001b[32m\"Greta Gerwig\"\u001b[39m, rating: \u001b[33m8.3\u001b[39m, length: \u001b[33m135\u001b[39m }\n",
       "  }\n",
       "]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await selfQueryRetriever.invoke(\n",
    "  \"Which movies are directed by Greta Gerwig?\"\n",
    ");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "420a6906-66fb-449f-8626-2e399ae5e6a8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\n",
       "  Document {\n",
       "    pageContent: \u001b[32m\"Toys come alive and have a blast doing so\"\u001b[39m,\n",
       "    metadata: { year: \u001b[33m1995\u001b[39m, genre: \u001b[32m\"animated\"\u001b[39m, length: \u001b[33m77\u001b[39m }\n",
       "  }\n",
       "]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await selfQueryRetriever.invoke(\n",
    "  \"Which movies are either comedy or drama and are less than 90 minutes?\"\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7f646a2",
   "metadata": {},
   "source": [
    "## Next steps\n",
    "\n",
    "You've now seen how to use the `SelfQueryRetriever` to to generate vector store filters based on an original question.\n",
    "\n",
    "Next, you can check out the list of [vector stores that currently support self-querying](/docs/integrations/retrievers/self_query/)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Deno",
   "language": "typescript",
   "name": "deno"
  },
  "language_info": {
   "file_extension": ".ts",
   "mimetype": "text/x.typescript",
   "name": "typescript",
   "nb_converter": "script",
   "pygments_lexer": "typescript",
   "version": "5.3.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
